package com.wh1200.mybatis.xmlless.util

import com.wh1200.mybatis.xmlless.model.XmllessTableInfo
import com.wh1200.mybatis.xmlless.model.base.BaseClassWrapper


/**
 * @author 吴昊
 * @date 2024/01/19
 * @version 1.0
 * @since v4.0.0
 */
object TableInfoProvider {

  private val TABLE_INFO_CACHE_MAP = mutableMapOf<String, XmllessTableInfo>()

  /**
   * @param tableName
   * @return
   */
  fun getXmllessTableInfoByTableName(tableName: String): XmllessTableInfo? {
    return TABLE_INFO_CACHE_MAP.values.find { it.simpleTableName == tableName }
  }

  /**
   * @param className
   * @return
   */
  fun getXmllessTableInfo(className: String): XmllessTableInfo {
    if (!TABLE_INFO_CACHE_MAP.containsKey(className)) {
      error("无法获取实体类${className}的TableInfo")
    }
    return TABLE_INFO_CACHE_MAP[className]!!
  }

  /**
   * @param wrapper
   * @return
   */
  fun getOrInitXmllessTableInfo(
      wrapper: BaseClassWrapper, useCache: Boolean = true
  ): XmllessTableInfo {
    if (!TABLE_INFO_CACHE_MAP.containsKey(wrapper.getClassName()) || !useCache) {
      val newTableInfo = wrapper.initXmllessTableInfo()
      val allAlias = (newTableInfo.classFields.map {
        it.getJoinObjects().map {
          it.alias
        }
      }.flatten() + newTableInfo.tableFields.mapNotNull {
        it.joinObject
      }.map { it.getAlias() }).filter { it.isNotBlank() }
      val duplicateAlias = allAlias.groupBy { it }.mapValues { it.value.size }.filter { it.value > 1 }.keys
      if (duplicateAlias.isNotEmpty()) {
        error("实体类${wrapper.getClassName()}中存在重复的关联表别名${duplicateAlias.joinToString(",")}")
      }
      TABLE_INFO_CACHE_MAP[wrapper.getClassName()] = newTableInfo
    }
    return TABLE_INFO_CACHE_MAP[wrapper.getClassName()]!!
  }

  fun clearCache() {
    TABLE_INFO_CACHE_MAP.clear()
  }

}
